package ru.yandex.api.money.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author: Melnikov Ivan melnikov.ivan@gmail.com
 */
public class Operation {
	
	public static final int DIRECTION_UNKNOWN = 0;
    public static final int DIRECTION_IN = 1;
    public static final int DIRECTION_OUT = 2;
    
	private final int id;
    private int pattern_id = 0;
    private final Date date;
    private final String title;
    private int direction = DIRECTION_UNKNOWN;
    private double amount = -1;
    
	public Operation(JSONObject json) {
		try {
            id = json.getInt("operation_id");
            title = json.getString("title");
            date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(json.getString("datetime"));
        } catch (JSONException e) {
            throw new RuntimeException("Parsing failed", e);
        } catch (ParseException e) {
            throw new RuntimeException("Parsing failed", e);
        }

        try {
            pattern_id = Integer.parseInt(json.getString("pattern_id"));
        } catch (JSONException e) {
            // ignore
        }

        try {
            amount = json.getDouble("amount");
        } catch (JSONException e) {
            // ignore
        }

        try {
            direction = json.getString("direction").equals("in") ? DIRECTION_IN : DIRECTION_OUT;
        } catch (JSONException e) {
            // ignore
        }
	}

	public int getId() {
		return id;
	}

	public int getPattern_id() {
		return pattern_id;
	}

	public Date getDate() {
		return date;
	}

	public String getTitle() {
		return title;
	}

	public int getDirection() {
		return direction;
	}

	public double getAmount() {
		return amount;
	}

}
